package com.njitt.bysj.srevice;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.njitt.bysj.base.BaseService;
import com.njitt.bysj.bean.RoleBean;
import com.njitt.bysj.mapper.PermissionBeanMapper;
import com.njitt.bysj.mapper.RoleBeanMapper;
import com.njitt.bysj.query.RoleQuery;
import com.njitt.bysj.utils.AssertUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description:
 * @author: wyj
 * @time: 2022/3/20 17:23
 */
@Service
public class RoleService extends BaseService<RoleBean, Integer> {
    @Resource
    private RoleBeanMapper roleMapper;

    public Map<String, Object> roleQuery(RoleQuery roleQuery) {
        Map<String, Object> map = new HashMap<>(16);
        PageHelper.startPage(roleQuery.getPage(), roleQuery.getLimit());
        PageInfo<RoleBean> info = new PageInfo<>(roleMapper.selectByParams(roleQuery));
        map.put("code", 0);
        map.put("data", info.getList());
        map.put("msg", "success");
        map.put("count", info.getTotal());
        return map;
    }

    public Set<String> queryRoleNameByEmpId(Integer empId) {
        return roleMapper.queryRoleNameByEmpId(empId);
    }

    public void addRole(RoleBean roleBean) {
        AssertUtil.isTrue(StringUtils.isBlank(roleBean.getRoleName()), "角色名不不能为空");
        roleBean.setCreateDate(new Date());
        roleBean.setUpdateDate(new Date());
        Integer role = roleMapper.insertSelective(roleBean);
        AssertUtil.isTrue(role != 1, "添加失败");
    }

    public void updateRole(RoleBean roleBean) {
        AssertUtil.isTrue(roleBean.getId() == null || roleBean.getId() == 0, "id 不能为空");
        roleBean.setUpdateDate(new Date());
        AssertUtil.isTrue(StringUtils.isBlank(roleBean.getRoleName()), "权限名不能为空");
        roleMapper.updateByPrimaryKeySelective(roleBean);
    }

    public List<Map<String, Object>> queryAllRoles() {
        return roleMapper.queryAllRoles();
    }

    public List<Map<String, Object>> queryEmpRolesByEmpId(Integer empId) {
        AssertUtil.isTrue(empId == null, "数据有误");
        return roleMapper.queryEmpRolesByEmpId(empId);
    }


    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteBatchByIds(Integer[] ids) {
        AssertUtil.isTrue(ids == null || ids.length < 1, "待删除记录不存在");
        AssertUtil.isTrue(roleMapper.deleteBatch(ids) != ids.length, "删除失败");
    }


    public RoleBean queryRoleByRoleId(Integer roleId) {
        AssertUtil.isTrue(roleId == null, "这是第二个异常");
        RoleBean roleBean = roleMapper.queryRoleByRoleId(roleId);
        return roleBean;
    }

}
